package cn.togeek.generate.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.togeek.generate.api.model.TablePageDTO;
import cn.togeek.generate.api.service.ICodeGenerateService;
import cn.togeek.generate.mapper.CodeGenerateMapper;
import cn.togeek.generate.util.CodeGenerateUtils;
import cn.togeek.generate.util.PageResult;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

/**
 * @author hanle
 * @description
 * @date 2021/8/3 10:59
 * @Company 西安图迹信息科技有限公司
 */
@Service
public class CodeGenerateServiceImpl implements ICodeGenerateService {

   private final CodeGenerateMapper codeGenerateMapper;

   public CodeGenerateServiceImpl(CodeGenerateMapper codeGenerateMapper) {
      this.codeGenerateMapper = codeGenerateMapper;
   }

   @Override
   public PageResult queryTables(TablePageDTO dto) {
      Page<Map<String, Object>> page = new Page<>(dto.getPage(), dto.getLimit());
      IPage<Map<String, Object>> list = codeGenerateMapper.queryList(page, dto);

      return new PageResult(list);

   }

   public Map<String, String> queryTable(String tableName) {
      return codeGenerateMapper.queryTable(tableName);
   }

   public List<Map<String, String>> queryColumns(String tableName) {
      return codeGenerateMapper.queryColumns(tableName);
   }

   @Override
   public byte[] buildCode(String[] tables) {
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      ZipOutputStream zip = new ZipOutputStream(outputStream);
      for(String tableName : tables) {
         //查询表信息
         Map<String, String> table = queryTable(tableName);
         //查询列信息
         List<Map<String, String>> columns = queryColumns(tableName);
         //生成代码
         CodeGenerateUtils.buildCode(table, columns, zip);
      }

      IOUtils.closeQuietly(zip);
      return outputStream.toByteArray();
   }
}
